﻿using Microsoft.Extensions.Options;
using MongoDB.Driver;
using SubStationManagement.Server.Models;

namespace SubStationManagement.Server.Services
{
    public class HarmonicSampleService
    {
        private readonly IMongoCollection<HarmonicSample> _HarmonicSamplesCollection;

        public HarmonicSampleService(
            IOptions<SubStationDatabaseSettings> subStationDatabaseSettings)
        {
            var mongoClient = new MongoClient(
                subStationDatabaseSettings.Value.ConnectionString);

            var mongoDatabase = mongoClient.GetDatabase(
                subStationDatabaseSettings.Value.DatabaseName);

            _HarmonicSamplesCollection = mongoDatabase.GetCollection<HarmonicSample>(
                subStationDatabaseSettings.Value.HarmonicSamplesCollectionName);
        }

        public async Task<List<HarmonicSample>> GetAsync() =>
            await _HarmonicSamplesCollection.Find(_ => true).ToListAsync();

        public List<HarmonicSample> GetAll() =>
            _HarmonicSamplesCollection.Find(_ => true).ToList();

        public async Task<HarmonicSample?> GetAsync(string id) =>
            await _HarmonicSamplesCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

        public async Task CreateAsync(HarmonicSample newHarmonicSample) =>
            await _HarmonicSamplesCollection.InsertOneAsync(newHarmonicSample);

        public async Task UpdateAsync(string id, HarmonicSample updatedHarmonicSample) =>
            await _HarmonicSamplesCollection.ReplaceOneAsync(x => x.Id == id, updatedHarmonicSample);

        public async Task RemoveAsync(string id) =>
            await _HarmonicSamplesCollection.DeleteOneAsync(x => x.Id == id);
    }
}
